package com.fy56.platform.logistics.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fy56.platform.logistics.common.ResultModel;
import com.fy56.platform.logistics.mapper.InsuranceMapper;
import com.fy56.platform.logistics.model.Company;
import com.fy56.platform.logistics.model.Insurance;
import com.fy56.platform.logistics.model.PayOrder;
import com.fy56.platform.logistics.model.WeChatProgram;
import com.fy56.platform.logistics.service.wx.IInsuranceService;
import com.fy56.platform.logistics.utils.DateUtil;
import com.fy56.platform.logistics.utils.HttpClientUtils;
import com.fy56.platform.logistics.utils.MD5Util;
import com.fy56.platform.logistics.utils.StringUtil;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class InsuranceServiceImpl implements IInsuranceService {

    @Autowired
    public InsuranceMapper insuranceMapper;

    /**
     * 将接口返回的Map对象转换为 ResultModel
     *
     * @param resultMap
     * @return
     */
    private ResultModel getResultModel(Map<String, Object> resultMap){
        Integer code = 101;
        String message = "";
        Object objectContent  ="";
        if(resultMap != null && !resultMap.isEmpty()){
            Object successState = resultMap.get("success");
            if(Boolean.valueOf(successState.toString()) == true){
                code = 100;
            }
            message =  resultMap.get("message") == null ? "" :  resultMap.get("message").toString();
            objectContent =  resultMap.get("object") == null ? "" :  resultMap.get("object");
        }
        return new ResultModel(code, message, objectContent);
    }

    @Override
    public ResultModel loginInsuranceService(WeChatProgram weChatProgram, String loginName, String password, String applicationCode)throws Exception{
        ResultModel result = null;
        Map<String, String> params = Maps.newHashMap();
        params.put("loginName", loginName);
        params.put("password", MD5Util.getMD5Code(password));
        params.put("applicationCode", applicationCode);
        String postData = HttpClientUtils.post(weChatProgram.getPrivilegeUrl() + "/privilegeManager/queryCompanyByUser", params, null, 10000, 10000);
        if(StringUtil.isNotEmpty(postData)){
            Map<String, Object> resultMap = JSON.parseObject(postData);
            result = getResultModel(resultMap);
        }
        return result;
    }

    @Override
    public ResultModel queryInsuranceCompanyByCompanyBindingService(WeChatProgram weChatProgram, String companyCode)throws Exception{
        ResultModel result = null;
        Map<String, String> params = Maps.newHashMap();
        params.put("companyCode", companyCode);
        String postData = HttpClientUtils.post(weChatProgram.getInsuranceUrl() + "/queryParam/insuranceCompanyByCompanyBinding", params, null, 10000, 10000);
        if(StringUtil.isNotEmpty(postData)){
            Map<String, Object> resultMap = JSON.parseObject(postData);
            result = getResultModel(resultMap);
        }
        return result;
    }

    @Override
    public ResultModel insuranceCodeListService(WeChatProgram weChatProgram, Insurance insurance, String userName, String passpwrd, String insuranceCompanyId, String bindingFlag)throws Exception{
        ResultModel result = null;
        Company company = insurance.getCompany();
        Map<String, String> params = Maps.newHashMap();
        params.put("userName", userName);
        params.put("password", passpwrd);
        if(StringUtil.isNotEmpty(insuranceCompanyId)) {
            params.put("insuranceCompanyId", insuranceCompanyId + "");
        }
        if(StringUtil.isNotEmpty(bindingFlag)) {
            params.put("bindingFlag", bindingFlag + "");
        }
        String postData = HttpClientUtils.post(weChatProgram.getInsuranceUrl() + "/queryParam/insuranceCodeList", params, null, 10000, 10000);
        if(StringUtil.isNotEmpty(postData)){
            Map<String,Object> resultMap = JSON.parseObject(postData);
            result = getResultModel(resultMap);
        }
        System.out.println("保险列表查询地址：url:" + weChatProgram.getInsuranceUrl() + "/queryParam/insuranceCodeList");
        System.out.println("保险列表查询参数：params:" + params.toString());
        System.out.println("保险列表数据：" + postData);
        return result;
    }

    @Override
    public ResultModel queryInsuranceUserListService(WeChatProgram weChatProgram, Insurance insurance, String userName, String passpwrd, Integer insuranceUserType, String insuranceCodeId) throws Exception{
        ResultModel result = null;
        Company company = insurance.getCompany();
        Map<String, String> params = Maps.newHashMap();
        params.put("userName", userName);
        params.put("password", passpwrd);
        params.put("insuranceUserType", insuranceUserType + "");
        params.put("insuranceCodeId", insuranceCodeId);
        String postData = HttpClientUtils.post(weChatProgram.getInsuranceUrl() + "/queryParam/insuranceUserList", params, null, 10000, 10000);
        if(StringUtil.isNotEmpty(postData)){
            Map<String,Object> resultMap = JSON.parseObject(postData);
            result = getResultModel(resultMap);
        }
        return result;
    }

    @Override
    public ResultModel queryInsuranceCodeNoticeContent(WeChatProgram weChatProgram, Insurance insurance, String userName, String passpwrd, String insuranceCodeId)throws Exception{
        Company company = insurance.getCompany();
        Map<String, String> params = Maps.newHashMap();
        params.put("userName", userName);
        params.put("password", passpwrd);
        params.put("insuranceCodeId", insuranceCodeId);
        String postData = HttpClientUtils.post(weChatProgram.getInsuranceUrl() + "/queryParam/insuranceCodeNoticeContent", params, null, 10000, 10000);

        Integer code = 101; String message = ""; String objectContent  ="";
        if(StringUtil.isNotEmpty(postData)){
            Map<String,Object> resultMap = JSON.parseObject(postData);
            if(resultMap != null && !resultMap.isEmpty()){
                Object successState = resultMap.get("success");
                if(Boolean.valueOf(successState.toString()) == true){
                    code = 100;
                }
                message =  resultMap.get("message") == null ? "" :  resultMap.get("message").toString();
                objectContent = resultMap.get("object") == null ? "" :  resultMap.get("object").toString();
                objectContent = objectContent.replaceAll("&nbsp;","");
                objectContent = delHTMLTag(objectContent);
            }
        }
        return new ResultModel(code, message, objectContent);
    }

    @Override
    public ResultModel calculateService(WeChatProgram weChatProgram, Insurance insurance, String userName, String passpwrd, Integer insuranceCompanyId, Integer insuranceCodeId, Double sumInsured, String fromArea, String toArea) throws  Exception{
        ResultModel result = null;
        Company company = insurance.getCompany();
        Map<String, String> params = Maps.newHashMap();
        params.put("userName", userName);
        params.put("password", passpwrd);
        params.put("insuranceCompanyId", insuranceCompanyId + "");
        params.put("insuranceCodeId", insuranceCodeId + "");
        params.put("sumInsured", sumInsured + "");
        params.put("fromArea", fromArea);
        params.put("toArea", toArea);
        String postData = HttpClientUtils.post(weChatProgram.getInsuranceUrl() + "/ insuranceOrder/calculate", params, null, 10000, 10000);
        if(StringUtil.isNotEmpty(postData)){
            Map<String,Object> resultMap = JSON.parseObject(postData);
            result = getResultModel(resultMap);
        }
        return result;
    }

    @Override
    public ResultModel addInsuranceService(WeChatProgram weChatProgram, Insurance insurance, String userName, String passpwrd, String data, String calculateWithArea, String consignmentNumber) throws  Exception{
        ResultModel result = null;
        // 1 查询该业务编号的 表单是否存在
        Insurance searchInsurance = new Insurance();
        searchInsurance.setConsignmentNumber(consignmentNumber);
        List<Insurance> insurances = insuranceMapper.findList(searchInsurance);
        if(insurances == null || insurances.size() ==0) {
            Company company = insurance.getCompany();
            Map<String, String> params = Maps.newHashMap();
            params.put("userName", userName);
            params.put("password", passpwrd);
            params.put("timestamp", System.currentTimeMillis() + "");
            params.put("data", data);
            params.put("calculateWithArea", calculateWithArea);
            String postData = HttpClientUtils.post(weChatProgram.getInsuranceUrl() + "/insuranceOrder/add", params, null, 20000, 20000);

            Integer code = 101;
            String message = "";
            Object content = null;
            if (StringUtil.isNotEmpty(postData)) {
                Map<String, Object> resultMap = JSON.parseObject(postData);
                if (resultMap != null && !resultMap.isEmpty()) {
                    // 1 封装要保存的投保订单信息。
                    Insurance insuranceEntity = JSON.parseObject(data, Insurance.class);
                    insuranceEntity.setRequestData(data);
                    insuranceEntity.setResponseData(postData);
                    insuranceEntity.setCreateTime(new Date());
                    insuranceEntity.setCode(userName);

                    // 2 获取object中的值 添加到insuranceEntity中
                    Map<String, Object> obMap = null;
                    Integer stateFlag = 0; String insuranceBillUrl="", transactionOrderNo="",insuranceBillCode="";
                    try{
                        if(resultMap.get("object") != null) {
                            obMap = JSON.parseObject(resultMap.get("object").toString());
                        }
                        if(obMap != null){
                            stateFlag          = obMap.get("stateFlag")!= null? Integer.parseInt(obMap.get("stateFlag").toString()):0;
                            insuranceBillUrl   = obMap.get("insuranceBillUrl")!= null? obMap.get("insuranceBillUrl").toString():"";
                            transactionOrderNo = obMap.get("transactionOrderNo")!= null? obMap.get("transactionOrderNo").toString():"";
                            insuranceBillCode  = obMap.get("insuranceBillCode")!= null? obMap.get("insuranceBillCode").toString():"";
                            insuranceEntity.setStateFlag(stateFlag);
                            insuranceEntity.setInsuranceBillUrl(insuranceBillUrl);
                            insuranceEntity.setTransactionOrderNo(transactionOrderNo);
                            insuranceEntity.setInsuranceBillCode(insuranceBillCode);
                        }
                    }catch (Exception ex){}

                    // 2 验证投保执行状态，并保存信息
                    Object successState = resultMap.get("success");
                    if (Boolean.valueOf(successState.toString()) == true) {
                        insuranceMapper.insertSelective(insuranceEntity);
                        code = 100;
                    } else {
                        if (resultMap.get("object") != null && obMap != null && 3 == stateFlag) {
                            insuranceMapper.insertSelective(insuranceEntity);
                            code = 100;
                        }
                    }
                    message = resultMap.get("message") == null ? "" : resultMap.get("message").toString();
                    content = resultMap.get("object");
                }
            }
            result = new ResultModel(code, message, content);

            System.out.println("InsuranceServiceImpl-->addInsuranceService投保访问参数: " + params.toString());
            System.out.println("InsuranceServiceImpl-->addInsuranceService投保返回结果: " + postData);
        }else{
            result = new ResultModel(101, "业务编号：transactionOrderNo="+ consignmentNumber +" 保单已存在。", null);
        }
        return result;
    }

    @Override
    public ResultModel queryCompanyAccountService(WeChatProgram weChatProgram, String userName, String passpwrd, String typeCode) throws  Exception{
        ResultModel result = null;
        Map<String, String> params = Maps.newHashMap();
        params.put("loginName", userName);
        params.put("password", passpwrd);
        params.put("typeCode", typeCode + "");
        String postData = HttpClientUtils.post(weChatProgram.getTradingcenterUrl() + "/consumeManager/queryCompanyAccount", params, null, 10000, 10000);
        if(StringUtil.isNotEmpty(postData)){
            Map<String,Object> resultMap = JSON.parseObject(postData);
            Boolean success = (Boolean) resultMap.get("success");
            Object balance = null;
            if(success){
                // 获取查询余额返回对象
                Object object = resultMap.get("object");
                Map<String, Object> objectMap = JSONObject.parseObject(object.toString(), Map.class);
                String consumeModel = objectMap.get("consumeModel") != null ? objectMap.get("consumeModel").toString() : "";
                if("总账户扣款".equals(consumeModel)){
                    // 获取总公司账户余额信息
                    Object consumeCompany =  objectMap.get("consumeCompanyBalance");
                    Map<String, Object> consumeCompanyBalance = JSONObject.parseObject(consumeCompany.toString(), Map.class);
                    balance = consumeCompanyBalance != null ? consumeCompanyBalance.get("balance"): null;
                }else {
                    balance = objectMap.get("balance");
                }
                result = new ResultModel(100, "余额查询成功", balance);
            }else {
                result = new ResultModel(101, "余额查询失败", balance);
            }
        }
        return result;
    }

        @Override
    public ResultModel queryOneService(WeChatProgram weChatProgram, Insurance insurance, String userName, String passpwrd, String transactionOrderNo) throws  Exception{
        ResultModel result = null;
        // 1 查询数据库中是否存在该保单
        insurance.setTransactionOrderNo(transactionOrderNo);
        List<Insurance> insuranceList = insuranceMapper.findList(insurance);
        if(insuranceList != null && insuranceList.size() > 0){
            Insurance resultEntity = insuranceList.get(0);
            Company company = insurance.getCompany();
            Map<String, String> params = Maps.newHashMap();
            params.put("userName", userName);
            params.put("password", passpwrd);
            params.put("transactionOrderNo", new Date().getTime()+"");
            String postData = HttpClientUtils.post(weChatProgram.getInsuranceUrl() + "/insuranceOrder/queryOne", params, null, 10000, 10000);
            Integer code = 101; String message = "";
            if(StringUtil.isNotEmpty(postData)){
                Map<String,Object> resultMap = JSON.parseObject(postData);
                result = getResultModel(resultMap);
            }
        }else {
            result = new ResultModel(101,"保单信息 transactionOrderNo=" +transactionOrderNo + ", 不存在", null);
        }
        return result;
    }

    @Override
    public ResultModel queryListService(WeChatProgram weChatProgram, Insurance insurance, String userName, String passpwrd, String startDate, String endDate, Integer stateFlag, Integer page, Integer pageSize) throws  Exception{
        ResultModel result = null;
        // 1 查询数据库中是否存在该保单
        Company company = insurance.getCompany();
        Map<String, String> params = Maps.newHashMap();
        params.put("userName", userName);
        params.put("password", passpwrd);
        params.put("startDate", startDate);
        params.put("endDate", endDate);
        if(stateFlag != null){
            params.put("stateFlag", stateFlag +"");
        }
        if(page != null){
            params.put("page", page +"");
        }
        if(pageSize != null){
            params.put("pageSize", pageSize +"");
        }
        String postData = HttpClientUtils.post(weChatProgram.getInsuranceUrl() + "/insuranceOrder/queryList", params, null, 10000, 10000);
        Integer code = 101; String message = "";
        if(StringUtil.isNotEmpty(postData)){
            Map<String,Object> resultMap = JSON.parseObject(postData);
            result = getResultModel(resultMap);
        }
        return result;
    }

    @Override
    public ResultModel updateInsuranceResultNoticeService(String consignmentNumber, String insuranceBillCode, String transactionOrderNo, Integer stateFlag, String insuranceBillUrl, String insuranceNoticeData)throws Exception{
        ResultModel result = null;
        Insurance insurance = insuranceMapper.getInsuranceByConsignmentNumber(consignmentNumber);
        if(insurance != null){
            insurance.setInsuranceBillCode(insuranceBillCode);
            insurance.setTransactionOrderNo(transactionOrderNo);
            insurance.setStateFlag(stateFlag);
            insurance.setInsuranceBillUrl(insuranceBillUrl);
            insurance.setInsuranceNoticeData(insuranceNoticeData);
            Integer updateCount = insuranceMapper.updateInsuranceNoticeContent(insurance);
            if(updateCount > 0){
                result = new ResultModel(100,"数据回投成功",null);
            }else{
                result = new ResultModel(101,"数据回投失败",null);
            }
            System.out.println("保险单信息：" +insurance.toString());
        }else {
            result = new ResultModel(101,"投保数据业务编号为：consignmentNumber=" + consignmentNumber + ", 数据不存在。",null);
        }
        return result;
    }

    /**
     * 去除html标签方法
     *
     * @param htmlContent
     * @return
     */
    public String delHTMLTag(String htmlContent){
        String result = "";
        if (StringUtil.isNotEmpty(htmlContent)) {
            String regEx_script = "<script[^>]*?>[\\s\\S]*?<\\/script>"; //定义script的正则表达式
            String regEx_style = "<style[^>]*?>[\\s\\S]*?<\\/style>"; //定义style的正则表达式
            String regEx_html = "<[^>]+>"; //定义HTML标签的正则表达式
            Pattern p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
            Matcher m_script = p_script.matcher(htmlContent);
            htmlContent = m_script.replaceAll(""); //过滤script标签
            Pattern p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
            Matcher m_style = p_style.matcher(htmlContent);
            htmlContent = m_style.replaceAll(""); //过滤style标签
            Pattern p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
            Matcher m_html = p_html.matcher(htmlContent);
            htmlContent = m_html.replaceAll(""); //过滤html标签
            result = htmlContent.trim();
        }
        return result; //返回文本字符串
    }

    @Override
    public PayOrder selectByPrimaryKey(Long id) {
        return null;
    }
    @Override
    public PayOrder get(PayOrder entity) {
        return null;
    }
    @Override
    public ResultModel update(PayOrder entity) {
        return null;
    }
    @Override
    public ResultModel updateSelective(PayOrder entity) { return null; }
    @Override
    public ResultModel delete(Long id) {
        return null;
    }
    @Override
    public ResultModel delete(PayOrder entity) {
        return null;
    }
    @Override
    public ResultModel insert(PayOrder entity){
        return null;
    }
    @Override
    public ResultModel insertSelective(PayOrder entity) {
        return null;
    }
    @Override
    @Transactional(readOnly = true)
    public List<PayOrder> findList(PayOrder entity) {
        return null;
    }

}
